#include "GSRDevice.h"
#include <QDateTime>
#include <QDebug>
#include <QMetaEnum>
#include <QLoggingCategory>
#include <QBluetoothLocalDevice>
#include <QEventLoop>
#include <QLibrary>
#include <QOperatingSystemVersion>
#include <QRegularExpression>
#include <qthread.h>

// 设备信息
#define DEVICE_NAME "OT09 Demo"
#define DEVICE_ADDRESS "C4:91:73:C9:50:D8"

// 特征UUID
#define UART_SERVICE_UUID "6e400000-b5a3-f393-e0a9-e50e24dcca9e"
#define UART_TX_CHAR_UUID "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
#define UART_RX_CHAR_UUID "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
#define STATUS_CHAR_UUID "00001534-1212-efde-1523-785feabcd123"

// 客户端特征配置描述符UUID
#define CLIENT_CHARACTERISTIC_CONFIG "00002902-0000-1000-8000-00805f9b34fb"


GSRDevice::GSRDevice(QObject *parent)
    : BioSignalDevice(parent),
    m_discoveryAgent(nullptr),
    m_controller(nullptr),
    m_uartService(nullptr),
    m_deviceName(DEVICE_NAME),
    m_deviceAddress(DEVICE_ADDRESS),
    m_connected(false),
    m_acquiring(false),
    m_scanning(false),
    m_connectionRetryCount(0),
    m_startTime(0),
    m_dataRequestTimer(new QTimer()), // 移除this，使定时器没有父对象，可以移动到线程
    m_connectionTimeoutTimer(new QTimer(this)),
    m_scanTimeoutTimer(new QTimer(this)),
    m_dataRequestInterval(50),  // 修改：从25ms改为50ms，进一步错开与ECG的通信
    m_samplingRate(100),
    m_actualSamplingRate(0.0),
    m_lastDataTimestamp(0),
    m_dataCountSinceLastCheck(0),
    m_samplingRateCheckTimer(new QTimer()), // 移除this，使定时器没有父对象，可以移动到线程
    m_chartUpdateTimer(new QTimer(this)),
    m_chartUpdatePending(false),
    m_notificationEnabled(false),
    m_acquisitionStartPending(false),
    m_waitingForWakeupResponse(false),
    m_dataRequestActive(false),
    m_lastRequestTime(0)  // 新增：跟踪上次请求时间
{
    // 启用蓝牙调试日志
    QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth.critical = true"));

    // 初始化蓝牙后端
    initializeBluetoothBackend();

    // 创建设备发现代理
    m_discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
    QObject::connect(m_discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,
                     this, &GSRDevice::onDeviceDiscovered);
    QObject::connect(m_discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished,
                     this, &GSRDevice::onScanFinished);
    QObject::connect(m_discoveryAgent, QOverload<QBluetoothDeviceDiscoveryAgent::Error>::of(&QBluetoothDeviceDiscoveryAgent::errorOccurred),
                     this, &GSRDevice::onScanError);

    // 设置定时器
    m_connectionTimeoutTimer->setSingleShot(true);
    m_connectionTimeoutTimer->setInterval(10000); // 10秒连接超时
    QObject::connect(m_connectionTimeoutTimer, &QTimer::timeout, this, [this]() {
        if (!m_connected && m_controller) {
            logMessage("连接超时");

            if (m_connectionRetryCount < MAX_CONNECTION_RETRIES) {
                m_connectionRetryCount++;
                logMessage(QString("尝试重新连接 (第 %1 次重试)").arg(m_connectionRetryCount));

                if (m_controller) {
                    m_controller->disconnectFromDevice();
                    QTimer::singleShot(1000, this, [this]() {
                        if (!m_connected && m_controller) {
                            m_controller->connectToDevice();
                            m_connectionTimeoutTimer->start();
                        }
                    });
                }
            } else {
                logMessage("达到最大重试次数，连接失败");
                emit errorOccurred("连接设备超时，请确认设备已开启并在范围内");
            }
        }
    });

    m_scanTimeoutTimer->setSingleShot(true);
    m_scanTimeoutTimer->setInterval(10000); // 10秒扫描超时
    QObject::connect(m_scanTimeoutTimer, &QTimer::timeout, this, [this]() {
        if (m_scanning && m_discoveryAgent->isActive()) {
            m_discoveryAgent->stop();
            logMessage("扫描超时");
        }
    });

    // 配置数据请求定时器 - 将在线程中启动
    m_dataRequestTimer->setInterval(m_dataRequestInterval);
    m_dataRequestTimer->setObjectName("GSRDataRequestTimer");

    // 使用队列连接，确保信号在接收者的线程中处理
    /*QObject::connect(m_dataRequestTimer, &QTimer::timeout,
                     this, &GSRDevice::requestDataOnce,
                     Qt::QueuedConnection);*/

    // 设置采样率检查定时器 - 将在线程中启动
    m_samplingRateCheckTimer->setInterval(1000); // 每秒检查一次采样率
    m_samplingRateCheckTimer->setObjectName("GSRSamplingRateCheckTimer");

    QObject::connect(m_samplingRateCheckTimer, &QTimer::timeout,
                     this, &GSRDevice::checkSamplingRate,
                     Qt::QueuedConnection);

    // 设置图表更新定时器
    m_chartUpdateTimer->setSingleShot(true);
    m_chartUpdateTimer->setInterval(50); // 50ms更新间隔
    QObject::connect(m_chartUpdateTimer, &QTimer::timeout, this, &GSRDevice::scheduleChartUpdate);

    // 设置线程连接
    setupThreadConnections();
}

// 修改析构函数，确保安全删除定时器
GSRDevice::~GSRDevice()
{
    // 确保停止采集和断开连接
    if (m_acquiring) {
        stopAcquisition();
    }

    if (m_connected) {
        disconnect();
    }

    // 停止所有定时器
    m_dataRequestTimer->stop();
    m_connectionTimeoutTimer->stop();
    m_scanTimeoutTimer->stop();
    m_samplingRateCheckTimer->stop();
    m_chartUpdateTimer->stop();

    // 删除没有父对象的定时器
    delete m_dataRequestTimer;
    delete m_samplingRateCheckTimer;

    // 清理资源
    if (m_controller) {
        m_controller->disconnectFromDevice();
        m_controller->deleteLater();
        m_controller = nullptr;
    }

    if (m_discoveryAgent) {
        if (m_discoveryAgent->isActive()) {
            m_discoveryAgent->stop();
        }
        m_discoveryAgent->deleteLater();
        m_discoveryAgent = nullptr;
    }
}

bool GSRDevice::initializeBluetoothBackend()
{
    const char* backend = "winrt";

    qputenv("QT_BLUETOOTH_BACKEND", backend);

    QBluetoothLocalDevice localDevice;
    if (localDevice.isValid()) {
        logMessage(QString("成功初始化蓝牙后端: %1").arg(backend));

        // 检查蓝牙是否开启
        if (localDevice.hostMode() == QBluetoothLocalDevice::HostPoweredOff) {
            logMessage("警告: 蓝牙已关闭，请开启蓝牙");
        } else {
            logMessage(QString("蓝牙已开启，适配器: %1 (%2)")
                           .arg(localDevice.name())
                           .arg(localDevice.address().toString()));
        }

        return true;
    }

    logMessage("错误: 蓝牙后端初始化失败");
    return false;
}

void GSRDevice::startScan()
{
    if (m_scanning) {
        logMessage("扫描已在进行中");
        return;
    }

    // 清空已发现的设备
    m_discoveredDevices.clear();

    // 设置扫描参数
    m_discoveryAgent->setLowEnergyDiscoveryTimeout(5000); // 5秒扫描时间

    // 开始扫描
    logMessage("开始扫描BLE设备...");
    m_discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
    m_scanning = true;

    // 启动扫描超时定时器
    m_scanTimeoutTimer->start();
}

void GSRDevice::onDeviceDiscovered(const QBluetoothDeviceInfo &info)
{
    // 只处理BLE设备
    if (info.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
        QString name = info.name();
        QString address = info.address().toString();

        logMessage(QString("发现BLE设备: %1 (%2) - RSSI: %3").arg(name).arg(address).arg(info.rssi()));

        // 保存设备信息
        m_discoveredDevices[address] = info;

        // 检查是否是目标设备
        if (address == m_deviceAddress ||
            name.contains(m_deviceName, Qt::CaseInsensitive) ||
            name.contains("OT09", Qt::CaseInsensitive) ||
            name.contains("Demo", Qt::CaseInsensitive)) {

            logMessage(QString("找到目标设备: %1 (%2)").arg(name).arg(address));

            // 停止扫描
            if (m_discoveryAgent->isActive()) {
                m_discoveryAgent->stop();
                m_scanning = false;

                // 连接到设备
                if (!m_connected) {
                    m_deviceAddress = address;
                    m_deviceName = name;
                    createControllerForDevice(info);
                }
            }
        }
    }
}

void GSRDevice::onScanFinished()
{
    m_scanning = false;
    m_scanTimeoutTimer->stop();

    logMessage(QString("扫描完成，发现 %1 个BLE设备").arg(m_discoveredDevices.size()));

    // 如果没有找到目标设备，尝试使用已知地址创建设备
    if (!m_connected && !m_discoveredDevices.contains(m_deviceAddress)) {
        logMessage("未找到目标设备，尝试使用已知地址直接连接");

        // 创建设备信息
        QBluetoothDeviceInfo deviceInfo(QBluetoothAddress(m_deviceAddress), m_deviceName, 0);
        deviceInfo.setCoreConfigurations(QBluetoothDeviceInfo::LowEnergyCoreConfiguration);

        // 创建控制器并连接
        createControllerForDevice(deviceInfo);
    }
}

void GSRDevice::onScanError(QBluetoothDeviceDiscoveryAgent::Error error)
{
    m_scanning = false;
    m_scanTimeoutTimer->stop();

    QString errorString = m_discoveryAgent->errorString();
    logMessage(QString("扫描错误: %1 - %2").arg(error).arg(errorString));

    // 尝试使用已知地址创建设备
    logMessage("尝试使用已知地址直接连接");

    // 创建设备信息
    QBluetoothDeviceInfo deviceInfo(QBluetoothAddress(m_deviceAddress), m_deviceName, 0);
    deviceInfo.setCoreConfigurations(QBluetoothDeviceInfo::LowEnergyCoreConfiguration);

    // 创建控制器并连接
    createControllerForDevice(deviceInfo);
}

bool GSRDevice::createControllerForDevice(const QBluetoothDeviceInfo &deviceInfo)
{
    // 清理旧控制器
    if (m_controller) {
        m_controller->disconnectFromDevice();
        delete m_controller;
        m_controller = nullptr;
    }

    // 检查设备信息是否有效
    if (deviceInfo.address().isNull()) {
        logMessage("错误: 设备地址无效");
        return false;
    }

    // 创建控制器
    bool controllerCreated = false;

    try {
        // 尝试方法1: 使用createCentral
        m_controller = QLowEnergyController::createCentral(deviceInfo, this);
        if (m_controller) {
            logMessage("成功创建BLE控制器");
            controllerCreated = true;
        }
    } catch (const std::exception &e) {
        logMessage(QString("创建控制器异常: %1").arg(e.what()));
    } catch (...) {
        logMessage("创建控制器时发生未知异常");
    }

    if (!controllerCreated) {
        logMessage("创建控制器失败");
        return false;
    }

    // 设置控制器
    setupController();

    // 开始连接
    logMessage("开始连接到设备...");
    m_controller->connectToDevice();

    // 启动连接超时定时器
    m_connectionTimeoutTimer->start();

    return true;
}

void GSRDevice::setupController()
{
    if (!m_controller) {
        return;
    }

    // 连接控制器信号
    QObject::connect(m_controller, &QLowEnergyController::connected, this, [this]() {
        logMessage("BLE连接已建立，正在发现服务...");
        m_connectionTimeoutTimer->stop();
        m_controller->discoverServices();
    });

    QObject::connect(m_controller, &QLowEnergyController::disconnected, this, [this]() {
        logMessage("BLE连接已断开");
        m_connected = false;
        emit connectionStatusChanged(false);
    });

    QObject::connect(m_controller, &QLowEnergyController::serviceDiscovered,
                     this, &GSRDevice::onServiceDiscovered);

    QObject::connect(m_controller, &QLowEnergyController::stateChanged,
                     this, &GSRDevice::onControllerStateChanged);

    // 使用正确的信号连接语法
    QObject::connect(m_controller,
                     QOverload<QLowEnergyController::Error>::of(&QLowEnergyController::errorOccurred),
                     this, &GSRDevice::onErrorOccurred);
}

bool GSRDevice::connect()
{
    if (m_connected) {
        logMessage("设备已连接");
        return true;
    }

    // 重置连接重试计数
    m_connectionRetryCount = 0;

    if (!initializeBluetoothBackend()) {
        QString errorMsg = "错误: 无法初始化蓝牙后端，请检查系统蓝牙配置";
        logMessage(errorMsg);
        emit errorOccurred(errorMsg);
        return false;
    }

    logMessage(QString("尝试连接到设备: %1 (%2)").arg(m_deviceName).arg(m_deviceAddress));

    // 首先尝试扫描设备
    startScan();

    // 扫描是异步的，连接将在扫描完成后进行
    return true;
}

bool GSRDevice::disconnect()
{
    if (!m_connected) {
        return true;
    }

    // 如果正在采集，先停止采集
    if (m_acquiring) {
        stopAcquisition();
    }

    // 停止所有定时器
    m_dataRequestTimer->stop();
    m_connectionTimeoutTimer->stop();
    m_scanTimeoutTimer->stop();
    m_samplingRateCheckTimer->stop();
    m_chartUpdateTimer->stop();

    // 断开服务通知
    if (m_uartService) {
        if (m_txCharacteristic.isValid()) {
            QLowEnergyDescriptor notificationDesc = m_txCharacteristic.descriptor(
                QBluetoothUuid(CLIENT_CHARACTERISTIC_CONFIG));
            if (notificationDesc.isValid()) {
                m_uartService->writeDescriptor(notificationDesc, QByteArray::fromHex("0000"));
            }
        }
        m_uartService->deleteLater();
        m_uartService = nullptr;
    }

    // 断开控制器
    if (m_controller) {
        m_controller->disconnectFromDevice();
        m_controller->deleteLater();
        m_controller = nullptr;
    }

    m_connected = false;
    emit connectionStatusChanged(false);
    logMessage("设备已断开连接");

    return true;
}

bool GSRDevice::startAcquisition()
{
    if (!m_connected) {
        logMessage("错误: 设备未连接，无法开始采集");
        emit errorOccurred("设备未连接，无法开始采集");
        return false;
    }

    if (m_acquiring) {
        logMessage("已经在采集数据");
        return true;
    }

    // 验证服务和特征的有效性
    if (!m_uartService) {
        logMessage("错误: UART服务不可用");
        emit errorOccurred("UART服务不可用");
        return false;
    }

    if (!m_txCharacteristic.isValid()) {
        logMessage("错误: TX特征无效");
        emit errorOccurred("TX特征无效");
        return false;
    }

    if (!m_rxCharacteristic.isValid()) {
        logMessage("错误: RX特征无效");
        emit errorOccurred("RX特征无效");
        return false;
    }

    // 清空数据缓冲区
    m_dataBuffer.clear();
    m_validFrames.clear();

    // 重置采样率相关变量
    m_actualSamplingRate = 0.0;
    m_lastDataTimestamp = 0;
    m_dataCountSinceLastCheck = 0;
    m_chartUpdatePending = false;
    m_dataRequestActive = false;

    // 记录开始时间
    m_startTime = QDateTime::currentMSecsSinceEpoch();
    m_lastDataTimestamp = m_startTime;

    // 验证通知特征的属性
    if (!(m_txCharacteristic.properties() & QLowEnergyCharacteristic::Notify)) {
        logMessage("错误: TX特征不支持通知");
        emit errorOccurred("TX特征不支持通知");
        return false;
    }

    // 验证写入特征的属性
    if (!(m_rxCharacteristic.properties() & QLowEnergyCharacteristic::Write)) {
        logMessage("错误: RX特征不支持写入");
        emit errorOccurred("RX特征不支持写入");
        return false;
    }

    // 先检查通知描述符是否存在
    QLowEnergyDescriptor notificationDesc = m_txCharacteristic.descriptor(
        QBluetoothUuid(CLIENT_CHARACTERISTIC_CONFIG));

    if (!notificationDesc.isValid()) {
        logMessage("错误: 无法找到通知描述符");
        emit errorOccurred("无法找到通知描述符");
        return false;
    }

    // 添加描述符写入状态跟踪
    m_notificationEnabled = false;
    m_acquisitionStartPending = true;

    logMessage("启用通知描述符...");
    m_uartService->writeDescriptor(notificationDesc, QByteArray::fromHex("0100"));

    return true;
}

bool GSRDevice::stopAcquisition()
{
    if (!m_acquiring) {
        return true;
    }

    // 停止定时器
    m_dataRequestTimer->stop();
    m_samplingRateCheckTimer->stop();
    m_chartUpdateTimer->stop();

    // 重置请求状态
    m_dataRequestActive = false;

    // 取消通知订阅
    if (m_uartService && m_txCharacteristic.isValid()) {
        QLowEnergyDescriptor notificationDesc = m_txCharacteristic.descriptor(
            QBluetoothUuid(CLIENT_CHARACTERISTIC_CONFIG));

        if (notificationDesc.isValid()) {
            m_uartService->writeDescriptor(notificationDesc, QByteArray::fromHex("0000"));
        }
    }

    // 计算采集统计信息
    qint64 duration = QDateTime::currentMSecsSinceEpoch() - m_startTime;
    int validCount = 0;
    for (const auto &frame : m_validFrames) {
        if (frame.value("valid", true).toBool()) {
            validCount++;
        }
    }

    logMessage("=== 数据采集结束 ===");
    logMessage(QString("采集时长: %1秒").arg(duration / 1000.0, 0, 'f', 1));
    logMessage(QString("数据点数: %1").arg(m_dataBuffer.size()));
    logMessage(QString("有效数据点数: %1").arg(validCount));
    logMessage(QString("无效数据点数: %1").arg(m_validFrames.size() - validCount));

    if (!m_dataBuffer.isEmpty()) {
        double rate = m_dataBuffer.size() / (duration / 1000.0);
        logMessage(QString("平均采样率: %1Hz").arg(rate, 0, 'f', 1));
        logMessage(QString("实际采样率: %1Hz").arg(m_actualSamplingRate, 0, 'f', 1));
    }

    m_acquiring = false;
    emit acquisitionStatusChanged(false);

    return true;
}

void GSRDevice::onControllerStateChanged(QLowEnergyController::ControllerState state)
{
    QString stateName = QMetaEnum::fromType<QLowEnergyController::ControllerState>().valueToKey(state);
    logMessage(QString("BLE控制器状态变更: %1").arg(stateName));
}

void GSRDevice::onServiceDiscovered(const QBluetoothUuid &uuid)
{
    logMessage(QString("发现服务: %1").arg(uuid.toString()));

    // 检查是否是UART服务
    if (uuid.toString().toLower().contains(UART_SERVICE_UUID)) {
        logMessage("找到UART服务");

        // 创建服务对象
        if (m_uartService) {
            m_uartService->deleteLater();
        }

        m_uartService = m_controller->createServiceObject(uuid, this);

        if (m_uartService) {
            QObject::connect(m_uartService, &QLowEnergyService::stateChanged,
                             this, &GSRDevice::onServiceStateChanged);

            QObject::connect(m_uartService, &QLowEnergyService::characteristicChanged,
                             this, &GSRDevice::onCharacteristicChanged);

            QObject::connect(m_uartService, &QLowEnergyService::characteristicRead,
                             this, &GSRDevice::onCharacteristicRead);

            QObject::connect(m_uartService, &QLowEnergyService::characteristicWritten,
                             this, &GSRDevice::onCharacteristicWritten);
            QObject::connect(m_uartService,
                             QOverload<QLowEnergyService::ServiceError>::of(&QLowEnergyService::errorOccurred),
                             this, &GSRDevice::onServiceError);
            // 发现服务详情
            m_uartService->discoverDetails();
        } else {
            logMessage("错误: 无法创建UART服务对象");
            emit errorOccurred("无法创建UART服务对象");
        }
    }
}

void GSRDevice::onServiceStateChanged(QLowEnergyService::ServiceState state)
{
    QString stateName = QMetaEnum::fromType<QLowEnergyService::ServiceState>().valueToKey(state);
    logMessage(QString("服务状态变更: %1").arg(stateName));

    if (state == QLowEnergyService::RemoteServiceDiscovered) {
        // 服务详情已发现，查找特征
        QString serviceInfo = "服务特征:\n";
        bool foundTxCharacteristic = false;
        bool foundRxCharacteristic = false;

        foreach (const QLowEnergyCharacteristic &characteristic, m_uartService->characteristics()) {
            QString uuid = characteristic.uuid().toString();
            serviceInfo += QString("- 特征: %1\n").arg(uuid);

            QStringList properties;
            if (characteristic.properties() & QLowEnergyCharacteristic::Read)
                properties << "可读";
            if (characteristic.properties() & QLowEnergyCharacteristic::Write)
                properties << "可写";
            if (characteristic.properties() & QLowEnergyCharacteristic::Notify)
                properties << "通知";
            if (characteristic.properties() & QLowEnergyCharacteristic::WriteNoResponse)
                properties << "无响应写入";

            serviceInfo += QString("  属性: %1\n").arg(properties.join(", "));

            // 更严格的特征匹配逻辑
            if (uuid.toLower().contains(UART_TX_CHAR_UUID)) {
                // 必须是TX特征且支持通知
                if (characteristic.properties() & QLowEnergyCharacteristic::Notify) {
                    m_txCharacteristic = characteristic;
                    serviceInfo += "  (TX特征 - 用于接收数据)\n";
                    foundTxCharacteristic = true;
                } else {
                    serviceInfo += "  (TX特征 - 但不支持通知，跳过)\n";
                }
            } else if (uuid.toLower().contains(UART_RX_CHAR_UUID)) {
                // 必须是RX特征且支持写入
                if (characteristic.properties() & (QLowEnergyCharacteristic::Write | QLowEnergyCharacteristic::WriteNoResponse)) {
                    m_rxCharacteristic = characteristic;
                    serviceInfo += "  (RX特征 - 用于发送数据)\n";
                    foundRxCharacteristic = true;
                } else {
                    serviceInfo += "  (RX特征 - 但不支持写入，跳过)\n";
                }
            } else if (uuid.toLower().contains(STATUS_CHAR_UUID)) {
                m_statusCharacteristic = characteristic;
                serviceInfo += "  (状态特征)\n";
            }
        }

        logMessage(serviceInfo);

        // 如果没有找到精确匹配的特征，使用备用逻辑
        if (!foundTxCharacteristic) {
            logMessage("未找到精确的TX特征，尝试查找支持通知的特征...");
            foreach (const QLowEnergyCharacteristic &characteristic, m_uartService->characteristics()) {
                if (characteristic.properties() & QLowEnergyCharacteristic::Notify) {
                    m_txCharacteristic = characteristic;
                    logMessage(QString("使用特征 %1 作为TX特征(接收数据)").arg(characteristic.uuid().toString()));
                    foundTxCharacteristic = true;
                    break;
                }
            }
        }

        if (!foundRxCharacteristic) {
            logMessage("未找到精确的RX特征，尝试查找支持写入的特征...");
            foreach (const QLowEnergyCharacteristic &characteristic, m_uartService->characteristics()) {
                if (characteristic.properties() & (QLowEnergyCharacteristic::Write | QLowEnergyCharacteristic::WriteNoResponse)) {
                    m_rxCharacteristic = characteristic;
                    logMessage(QString("使用特征 %1 作为RX特征(发送数据)").arg(characteristic.uuid().toString()));
                    foundRxCharacteristic = true;
                    break;
                }
            }
        }

        // 检查是否找到所需特征
        if (!foundTxCharacteristic || !foundRxCharacteristic) {
            logMessage("错误: 未找到所需的UART特征");
            emit errorOccurred("未找到所需的UART特征");
            return;
        }

        // 验证特征的描述符
        QLowEnergyDescriptor notificationDesc = m_txCharacteristic.descriptor(
            QBluetoothUuid(CLIENT_CHARACTERISTIC_CONFIG));

        if (!notificationDesc.isValid()) {
            logMessage("警告: TX特征没有通知描述符");
        } else {
            logMessage("TX特征通知描述符验证成功");
        }

        // 添加描述符写入信号连接
        QObject::connect(m_uartService, &QLowEnergyService::descriptorWritten,
                         this, &GSRDevice::onDescriptorWritten);

        // 尝试读取设备状态
        if (m_statusCharacteristic.isValid() && (m_statusCharacteristic.properties() & QLowEnergyCharacteristic::Read)) {
            logMessage("读取设备状态特征...");
            m_uartService->readCharacteristic(m_statusCharacteristic);
        }

        // 连接成功
        m_connected = true;
        m_connectionRetryCount = 0;

        // 确保发送信号
        logMessage("设备连接成功，发送connectionStatusChanged信号");
        emit connectionStatusChanged(true);
    }
}

void GSRDevice::onCharacteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &value)
{
    // 处理特征值变化（通知）
    if (characteristic.uuid() == m_txCharacteristic.uuid()) {
        // 唤醒响应处理 - 这部分保留在主线程因为它修改了关键状态变量
        if (m_waitingForWakeupResponse) {
            logMessage(QString("等待唤醒响应时收到数据: %1").arg(value.toHex(' ').toUpper()));
            m_waitingForWakeupResponse = false;

            // 修改：直接调用startDataCollection而不是使用QMetaObject::invokeMethod
            startDataCollection();
        }

        // 首次接收数据的日志记录
        static int receivedCount = 0;
        receivedCount++;
        if (receivedCount == 1) {
            logMessage("*** 首次接收到数据，数据通道工作正常 ***");
        }

        // 发射信号，让工作线程处理数据
        emit dataReceived(value);
    } else {
        // 记录意外的特征变化
        logMessage(QString("收到意外特征变化: %1").arg(characteristic.uuid().toString()));
    }
}

void GSRDevice::onCharacteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &value)
{
    QString uuid = characteristic.uuid().toString();

    if (characteristic.uuid() == m_statusCharacteristic.uuid()) {
        // 读取到状态特征
        QString statusHex;
        for (int i = 0; i < value.size(); i++) {
            statusHex += QString("%1 ").arg((quint8)value.at(i), 2, 16, QChar('0')).toUpper();
        }

        logMessage(QString("设备状态: %1").arg(statusHex.trimmed()));

        // 判断设备状态
        if (statusHex.trimmed() == "01 00") {
            logMessage("设备状态正常，可以开始采集");
        } else {
            logMessage("设备状态: " + statusHex.trimmed());
        }
    }
}

void GSRDevice::onCharacteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &value)
{
    if (characteristic.uuid() == m_rxCharacteristic.uuid()) {
        static int writeCount = 0;
        writeCount++;

        // 只在前5次和每1000次时输出日志
        if (writeCount <= 5 || writeCount % 1000 == 0) {
            QString hexData = value.toHex(' ').toUpper();
            logMessage(QString("写入RX特征成功 #%1: %2").arg(writeCount).arg(hexData));
        }
        // 每次写入成功后，立即请求下一次数据（如果正在采集）
        if (m_acquiring && m_notificationEnabled) {
            // 使用短延迟避免过于频繁的请求
            QTimer::singleShot(1, this, &GSRDevice::requestDataOnce);
        }
    }
}


void GSRDevice::onErrorOccurred(QLowEnergyController::Error error)
{
    QString errorName = QMetaEnum::fromType<QLowEnergyController::Error>().valueToKey(error);
    QString errorMessage = QString("BLE控制器错误: %1").arg(errorName);

    // 添加更详细的错误信息
    if (error == QLowEnergyController::InvalidBluetoothAdapterError) {
        errorMessage += "\n可能的原因:\n";
        errorMessage += "1. 蓝牙适配器未开启或不可用\n";
        errorMessage += "2. 需要管理员权限访问蓝牙\n";
        errorMessage += "3. Qt 蓝牙后端配置问题\n";

        // 检查蓝牙适配器状态
        QBluetoothLocalDevice localDevice;
        if (localDevice.isValid()) {
            errorMessage += QString("本地蓝牙设备: %1 (%2)\n").arg(localDevice.name()).arg(localDevice.address().toString());

            if (localDevice.hostMode() == QBluetoothLocalDevice::HostPoweredOff) {
                errorMessage += "蓝牙适配器已关闭，请开启蓝牙";
            } else {
                errorMessage += "蓝牙适配器已开启，但Qt无法访问";
            }
        } else {
            errorMessage += "未检测到有效的蓝牙适配器";
        }
    } else if (error == QLowEnergyController::ConnectionError) {
        if (m_connectionRetryCount < MAX_CONNECTION_RETRIES) {
            m_connectionRetryCount++;
            logMessage(QString("连接错误，尝试重新连接 (第 %1 次重试)").arg(m_connectionRetryCount));

            // 延迟1秒后重新连接
            QTimer::singleShot(1000, this, [this]() {
                if (m_controller && !m_connected) {
                    m_controller->connectToDevice();
                    m_connectionTimeoutTimer->start();
                }
            });
            return;
        } else {
            errorMessage += "\n达到最大重试次数，连接失败";
        }
    } else if (error == QLowEnergyController::AdvertisingError) {
        errorMessage += "\n设备未广播或不在范围内";
    } else if (error == QLowEnergyController::RemoteHostClosedError) {
        errorMessage += "\n设备主动断开连接";
    }

    logMessage(errorMessage);
    emit errorOccurred(errorMessage);
}

void GSRDevice::onServiceError(QLowEnergyService::ServiceError error)
{
    QString errorName = QMetaEnum::fromType<QLowEnergyService::ServiceError>().valueToKey(error);
    QString errorMessage = QString("BLE服务错误: %1").arg(errorName);

    if (error == QLowEnergyService::CharacteristicWriteError) {
        errorMessage += "\n写入特征值失败，可能原因:";
        errorMessage += "\n1. 设备不支持该操作";
        errorMessage += "\n2. 设备已断开连接";
        errorMessage += "\n3. 数据格式错误";
    } else if (error == QLowEnergyService::DescriptorWriteError) {
        errorMessage += "\n写入描述符失败，无法启用通知";
    }

    logMessage(errorMessage);
    emit errorOccurred(errorMessage);
}

void GSRDevice::requestData()
{
    // 这个方法保留但不再使用定时器调用
    // 改为使用requestDataOnce方法
    requestDataOnce();
}

void GSRDevice::requestDataOnce()
{
    // 调整请求间隔避免与ECG冲突
    static qint64 lastRequestTime = 0;
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();

    // 确保请求间隔至少50ms，避免与ECG设备冲突
    if (currentTime - lastRequestTime < 50) {
        return;
    }

    if (!m_connected || !m_acquiring || !m_uartService || !m_rxCharacteristic.isValid()) {
        return;
    }

    // 验证通知是否已启用
    if (!m_notificationEnabled) {
        return;
    }

    // 防止重复请求
    if (m_dataRequestActive) {
        return;
    }

    // 标记请求为活跃状态
    m_dataRequestActive = true;
    lastRequestTime = currentTime;

    QByteArray requestCommand;
    requestCommand.append((char)0x00);
    requestCommand.append((char)0x01);
    requestCommand.append((char)0x00);
    requestCommand.append((char)0x07);

    try {
        // 使用互斥锁保护蓝牙写入操作
        QMutexLocker locker(&m_bluetoothMutex);
        m_uartService->writeCharacteristic(m_rxCharacteristic, requestCommand);

        // 减少请求日志输出频率
        static int requestCount = 0;
        requestCount++;
        // 只在前5次和每1000次时输出日志
        if (requestCount <= 5 || requestCount % 1000 == 0) {
            logMessage(QString("已发送第 %1 次数据请求").arg(requestCount));
        }
    } catch (const std::exception &e) {
        logMessage(QString("发送数据请求异常: %1").arg(e.what()));
        m_dataRequestActive = false;  // 重置状态
    } catch (...) {
        logMessage("发送数据请求时发生未知异常");
        m_dataRequestActive = false;  // 重置状态
    }
}

void GSRDevice::processReceivedData(const QByteArray &data)
{
    // 此方法将在GSR设备线程中执行，而不是主线程

    if (!m_acquiring) {
        return;
    }

    // 重置请求状态，允许下一次请求
    m_dataRequestActive = false;

    // 获取当前时间戳
    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();

    // 打印原始数据值
    QString hexData = data.toHex(' ').toUpper();
    logMessage(QString("接收到原始数据: %1").arg(hexData));

    // 尝试将数据写入缓冲区，添加重试机制
    const int MAX_RETRY = 3;
    int retry_count = 0;

    while (retry_count < MAX_RETRY) {
        // 非阻塞写入尝试 - 这里我们实现为尝试处理数据
        if (tryWriteToBuffer(data, timestamp)) {
            break;
        }
        QThread::msleep(5);  // 短暂等待5毫秒
        retry_count++;
    }

    if (retry_count == MAX_RETRY) {
        logMessage("GSR数据写入超时，丢弃数据包");
        return;
    }

    // 更新采样率统计
    m_dataCountSinceLastCheck++;

    // 只打印前5个原始数据的调试信息
    static int debugCount = 0;
    debugCount++;
    if (debugCount <= 5) {
        logMessage(QString("=== 原始十六进制数据 #%1 ===").arg(debugCount));
        logMessage(QString("HEX: %1").arg(hexData));
        logMessage(QString("长度: %1 字节").arg(data.length()));
    }

    // 解析数据帧
    QVector<double> parsedData = parseDataFrameCorrect(data);

    if (!parsedData.isEmpty()) {
        // 检查是否有异常值（正值约11000）并修正
        for (int i = 0; i < parsedData.size(); i++) {
            // 如果值在异常范围内（正值且在10000-15000之间），尝试修正
            if (parsedData[i] > 10000 && parsedData[i] < 15000) {
                // 修正方法：将其转换为对应的负值（约-50000左右）
                // 这里使用简单的转换：将值减去65536（2^16）
                parsedData[i] -= 65536;

                // 调试日志
                if (debugCount <= 5) {
                    logMessage(QString("修正异常值: 索引 %1, 原值 %2, 修正后 %3")
                                   .arg(i).arg(parsedData[i] + 65536).arg(parsedData[i]));
                }
            }
        }

        // 发射与EDADevice一致的信号
        emit newDataReceived(parsedData, timestamp);

        // 保持原有的GSR特定信号发射，但移除调试输出
        if (m_startTime > 0) {
            // 发送数据信号 - 每个通道单独发送（静默）
            for (int i = 0; i < parsedData.size() && i < 6; i++) {
                QVector<double> channelData;
                channelData.append(parsedData[i]);
                emit dataReady(channelData, i);
            }

            // 发送所有通道的数据（静默）
            emit allChannelsDataReady(parsedData);

            // 为GSR图表添加特定格式的数据（静默）
            if (parsedData.size() >= 2) {
                QVector<double> gsrData;
                gsrData.append(parsedData[0]);  // 使用第一个通道作为GSR值1
                gsrData.append(parsedData[1]);  // 使用第二个通道作为GSR值2
                emit dataReady(gsrData, -2);  // 使用特殊通道索引-2表示GSR数据
            }

            // 安排图表更新 - 使用QMetaObject::invokeMethod确保在正确的线程中调用
            QMetaObject::invokeMethod(this, "scheduleChartUpdate", Qt::QueuedConnection);
        }
    }
}

// 尝试将数据写入缓冲区
bool GSRDevice::tryWriteToBuffer(const QByteArray &data, qint64 timestamp)
{
    try {
        // 存储原始数据到缓冲区
        m_dataBuffer.append(qMakePair(timestamp, data));
        return true;
    }
    catch (const std::exception &e) {
        logMessage(QString("写入缓冲区异常: %1").arg(e.what()));
        return false;
    }
    catch (...) {
        logMessage("写入缓冲区时发生未知异常");
        return false;
    }
}

QVector<double> GSRDevice::parseDataFrameCorrect(const QByteArray &data)
{
    QVector<double> result;

    // 转换为十六进制字符串（不带空格）
    QString hexData = data.toHex().toUpper();

    // **修正：添加静态调试计数器**
    static int debugCount = 0;
    debugCount++;

    // 添加重试机制，尝试处理可能不完整的数据帧
    const int MAX_RETRY = 3;
    for (int retry = 0; retry < MAX_RETRY; retry++) {
        // 如果数据长度不足，等待短暂时间后重试
        if (hexData.length() < 40) {
            if (retry < MAX_RETRY - 1) {
                QThread::msleep(5); // 短暂等待5毫秒
                continue;
            }

            // 最后一次尝试仍然失败
            if (debugCount <= 5) {
                logMessage(QString("数据长度不足: %1 字符，需要40字符").arg(hexData.length()));
            }
            return result;
        }

        // 数据长度足够，跳出重试循环
        break;
    }

    try {
        // **关键修改13：完全按照Python代码的解析逻辑**
        // 提取序列号(前2个字符)并转换为10进制
        bool ok;
        int sequence = hexData.mid(0, 2).toInt(&ok, 16);
        if (!ok) {
            return result;
        }

        // 提取校验码(第3-4个字符)
        QString checksum = hexData.mid(2, 2);

        // **关键修改14：使用Python代码相同的segment解析逻辑**
        // 每个segment占5个字符，从第5个字符开始
        int segment1 = hexToSignedIntPython(hexData.mid(5, 5));   // 第6-10个字符
        int segment2 = hexToSignedIntPython(hexData.mid(11, 5));   // 第12-16个字符
        int segment3 = hexToSignedIntPython(hexData.mid(17, 5));  // 第18-22个字符
        int segment4 = hexToSignedIntPython(hexData.mid(23, 5));  // 第24-28个字符
        int segment5 = hexToSignedIntPython(hexData.mid(29, 5));  // 第30-34个字符
        int segment6 = hexToSignedIntPython(hexData.mid(35, 5));  // 第36-40个字符

        // 创建帧数据结构
        QMap<QString, QVariant> frameData;
        frameData["timestamp"] = QDateTime::currentMSecsSinceEpoch();
        frameData["sequence"] = sequence;
        frameData["checksum"] = checksum;

        QVector<int> segments = {segment1, segment2, segment3, segment4, segment5, segment6};
        frameData["segments"] = QVariant::fromValue(segments);

        // **关键修改15：使用Python代码相同的校验逻辑**
        bool valid = (checksum.toLower() == "0e");
        frameData["valid"] = valid;

        if (valid) {
            // 有效帧，直接使用数据
            m_validFrames.append(frameData);

            // 限制队列大小
            if (m_validFrames.size() > 100) {
                m_validFrames.removeFirst();
            }

            // 转换为double并返回
            for (int seg : segments) {
                result.append(static_cast<double>(seg));
            }

            // **优化修改3：只打印前5次解析结果**
            static int parseCount = 0;
            parseCount++;
            if (parseCount <= 5) {
                QString formattedTime = QDateTime::fromMSecsSinceEpoch(frameData["timestamp"].toLongLong()).toString("HH:mm:ss.fff");
                logMessage(QString("=== 数据解析成功 #%1 ===").arg(parseCount));
                logMessage(QString("[%1] 序列号: %2, 校验位: %3 (有效)")
                               .arg(formattedTime).arg(sequence).arg(checksum));
                logMessage(QString("segment1: %1, segment2: %2, segment3: %3")
                               .arg(segment1).arg(segment2).arg(segment3));
                logMessage(QString("segment4: %1, segment5: %2, segment6: %3")
                               .arg(segment4).arg(segment5).arg(segment6));
            }

        } else {
            // **关键修改16：使用Python代码相同的无效帧处理逻辑**
            if (!m_validFrames.isEmpty()) {
                // 使用前一个有效帧的数据
                QMap<QString, QVariant> lastValidFrame;
                for (int i = m_validFrames.size() - 1; i >= 0; i--) {
                    if (m_validFrames[i].value("valid", false).toBool()) {
                        lastValidFrame = m_validFrames[i];
                        break;
                    }
                }

                if (!lastValidFrame.isEmpty()) {
                    QVector<int> lastSegments = lastValidFrame["segments"].value<QVector<int>>();

                    // 记录无效帧但使用前一帧数据
                    frameData["interpolated_segments"] = QVariant::fromValue(lastSegments);
                    m_validFrames.append(frameData);

                    // 转换为double并返回
                    for (int seg : lastSegments) {
                        result.append(static_cast<double>(seg));
                    }

                    // **优化修改4：只打印前3次插值结果**
                    static int interpolateCount = 0;
                    interpolateCount++;
                    if (interpolateCount <= 3) {
                        QString formattedTime = QDateTime::fromMSecsSinceEpoch(frameData["timestamp"].toLongLong()).toString("HH:mm:ss.fff");
                        logMessage(QString("=== 无效帧插值 #%1 ===").arg(interpolateCount));
                        logMessage(QString("[%1] 序列号: %2, 校验位: %3 (无效，使用前一帧)")
                                       .arg(formattedTime).arg(sequence).arg(checksum));
                    }
                }
            }
        }

    } catch (const std::exception &e) {
        logMessage(QString("数据解析异常: %1").arg(e.what()));
    } catch (...) {
        logMessage("数据解析时发生未知异常");
    }

    return result;
}

int GSRDevice::correctSegmentValue(int value, const QString &hexStr)
{
    // 如果值在正常范围内（负值或大于20000），则保持不变
    if (value < 0 || value > 20000) {
        return value;
    }

    // 尝试反转字节序重新解析
    // 原始解析是从左到右，现在尝试从右到左
    QString reversed;
    for (int i = hexStr.length() - 2; i >= 0; i -= 2) {
        reversed.append(hexStr.mid(i, 2));
    }

    bool ok;
    uint uValue = reversed.toUInt(&ok, 16);
    if (!ok) {
        return value; // 如果转换失败，返回原值
    }

    // 计算二进制补码
    int numBits = hexStr.length() * 4;
    if (uValue & (1U << (numBits - 1))) {
        return static_cast<int>(uValue) - (1 << numBits);
    }

    return static_cast<int>(uValue);
}



// **关键修改17：实现Python代码相同的有符号整数转换函数**
int GSRDevice::hexToSignedIntPython(const QString &hexStr)
{
    if (hexStr.isEmpty()) {
        return 0;
    }

    bool ok;
    uint value = hexStr.toUInt(&ok, 16);

    if (!ok) {
        return 0;
    }

    // **关键修改18：使用Python代码相同的位数计算**
    // Python代码使用的是动态位数：len(hex_str) * 4
    int numBits = hexStr.length() * 4;

    // 检查最高位是否为1（负数）
    if (value & (1U << (numBits - 1))) {
        // 计算二进制补码
        int result = static_cast<int>(value) - (1 << numBits);
        return result;
    }

    return static_cast<int>(value);
}

// 保留原有的转换函数以防其他地方使用
int GSRDevice::hexToSignedInt16(const QString &hexStr)
{
    if (hexStr.isEmpty()) {
        return 0;
    }

    bool ok;
    uint value = hexStr.toUInt(&ok, 16);

    if (!ok) {
        return 0;
    }

    const int numBits = 16;

    // 检查最高位是否为1（负数）
    if (value & (1U << (numBits - 1))) {
        // 计算二进制补码
        int result = static_cast<int>(value) - (1 << numBits);
        return result;
    }

    return static_cast<int>(value);
}

int GSRDevice::hexToSignedInt24(const QString &hexStr)
{
    if (hexStr.isEmpty()) {
        return 0;
    }

    bool ok;
    uint value = hexStr.toUInt(&ok, 16);

    if (!ok) {
        return 0;
    }

    const int numBits = 24;

    // 检查最高位是否为1（负数）
    if (value & (1U << (numBits - 1))) {
        // 计算二进制补码
        int result = static_cast<int>(value) - (1 << numBits);
        return result;
    }

    return static_cast<int>(value);
}

int GSRDevice::hexToSignedInt(const QString &hexStr)
{
    if (hexStr.isEmpty()) {
        return 0;
    }

    bool ok;
    uint value = hexStr.toUInt(&ok, 16);

    if (!ok) {
        return 0;
    }

    int numBits = 20;

    // 检查最高位是否为1（负数）
    if (value & (1U << (numBits - 1))) {
        // 计算二进制补码
        int result = static_cast<int>(value) - (1 << numBits);
        return result;
    }

    return static_cast<int>(value);
}

// 采样率检查方法
void GSRDevice::checkSamplingRate()
{
    if (!m_acquiring) {
        return;
    }

    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 timeDiff = currentTime - m_lastDataTimestamp;

    if (timeDiff > 0) {
        // 计算实际采样率
        m_actualSamplingRate = (m_dataCountSinceLastCheck * 1000.0) / timeDiff;

        // 减少日志输出频率
        static int checkCount = 0;
        checkCount++;
        if (checkCount % 60 == 0) {  // 每60秒记录一次
            logMessage(QString("实际采样率: %1Hz, 目标采样率: %2Hz")
                           .arg(m_actualSamplingRate, 0, 'f', 1)
                           .arg(m_samplingRate));
        }
    }

    // 重置计数器
    m_dataCountSinceLastCheck = 0;
    m_lastDataTimestamp = currentTime;
}

// 图表更新调度方法
void GSRDevice::scheduleChartUpdate()
{
    if (!m_chartUpdatePending) {
        m_chartUpdatePending = true;
        m_chartUpdateTimer->start();

        // 重置标志的回调
        QTimer::singleShot(m_chartUpdateTimer->interval(), this, [this]() {
            m_chartUpdatePending = false;
        });
    }
}

// 设置采样率方法
void GSRDevice::setSampleRate(int rate)
{
    m_samplingRate = rate;

    // **关键修改19：不再使用定时器间隔，因为改为基于响应的请求模式**
    logMessage(QString("采样率设置为 %1Hz (基于响应的请求模式)").arg(rate));
}

void GSRDevice::logMessage(const QString &message)
{
    qDebug() << "[GSRDevice]" << message;
    // 可以在这里添加更多日志记录逻辑，如写入文件等
}

QString GSRDevice::getDeviceInfo() const
{
    return QString("GSR设备 - %1 (%2) - %3")
        .arg(m_deviceName)
        .arg(m_deviceAddress)
        .arg(m_connected ? "已连接" : "未连接");
}

bool GSRDevice::startScanAndConnect()
{
    qDebug() << "GSRDevice::startScanAndConnect() 方法被调用";

    // 如果已经连接，直接返回成功
    if (m_connected) {
        emit connectionStatusChanged(true); // 确保发送信号
        return true;
    }

    // 重置连接重试计数
    m_connectionRetryCount = 0;

    // 尝试重新初始化蓝牙后端
    if (!initializeBluetoothBackend()) {
        QString errorMsg = "错误: 蓝牙不可用，请检查蓝牙硬件和驱动";
        logMessage(errorMsg);
        emit errorOccurred(errorMsg);
        return false;
    }

    // 开始连接过程
    bool result = connect();

    // 连接是异步的，这里返回的只是连接过程是否开始
    qDebug() << "GSR 连接过程已启动，等待异步结果...";
    return result;
}

bool GSRDevice::disconnectDevice()
{
    // 简单实现，直接调用disconnect方法
    return disconnect();
}

void GSRDevice::onDescriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue)
{
    logMessage(QString("描述符写入完成: %1, 值: %2")
                   .arg(descriptor.uuid().toString())
                   .arg(newValue.toHex().toUpper()));

    // 检查是否是通知描述符
    if (descriptor.uuid() == QBluetoothUuid(CLIENT_CHARACTERISTIC_CONFIG)) {
        if (newValue == QByteArray::fromHex("0100")) {
            // 通知已启用
            m_notificationEnabled = true;
            logMessage("通知描述符启用成功");

            // 如果是在启动采集过程中
            if (m_acquisitionStartPending) {
                m_acquisitionStartPending = false;

                // **关键修改20：发送唤醒命令**
                logMessage("发送设备唤醒命令...");

                QByteArray wakeupCommand;
                wakeupCommand.append((char)0x00);
                wakeupCommand.append((char)0x01);
                wakeupCommand.append((char)0x00);
                wakeupCommand.append((char)0x07);

                // 使用标准写入模式
                m_uartService->writeCharacteristic(m_rxCharacteristic, wakeupCommand);

                // 设置等待唤醒响应标志
                m_waitingForWakeupResponse = true;

                // 启动唤醒超时定时器
                QTimer::singleShot(3000, this, [this]() {
                    if (m_waitingForWakeupResponse) {
                        logMessage("唤醒命令响应超时，继续采集流程");
                        m_waitingForWakeupResponse = false;
                        startDataCollection();
                    }
                });

                logMessage("唤醒命令已发送，等待设备响应...");
            }
        } else if (newValue == QByteArray::fromHex("0000")) {
            // 通知已禁用
            m_notificationEnabled = false;
            logMessage("通知描述符禁用成功");
        }
    }
}

void GSRDevice::startDataCollection()
{
    if (m_notificationEnabled && !m_acquiring) {
        // 现在开始真正的数据采集
        m_acquiring = true;
        emit acquisitionStatusChanged(true);

        logMessage("=== 数据采集开始 ===");
        logMessage("使用基于响应的数据请求模式");

        // 立即发送第一次数据请求
        QMetaObject::invokeMethod(this, "requestDataOnce", Qt::QueuedConnection);

        // 启动采样率监控定时器
        m_samplingRateCheckTimer->start();
    }
}

QVector<double> GSRDevice::parseDataFrame(const QByteArray &data)
{
    // 重定向到正确的解析方法
    return parseDataFrameCorrect(data);
}

void GSRDevice::tryInterpolateFrame(int invalidFrameIdx)
{
    // 保留这个方法以防其他地方调用
}

// 添加一个新方法用于设置线程连接
void GSRDevice::setupThreadConnections()
{
    // 确保处理数据的方法在GSR设备的线程中执行
    QObject::connect(this, &GSRDevice::dataReceived,
                     this, &GSRDevice::processReceivedData,
                     Qt::QueuedConnection);
}

// 添加新方法用于将定时器移动到线程
void GSRDevice::moveToThread(QThread* thread)
{
    // 将设备对象移动到线程
    QObject::moveToThread(thread);

    // 将定时器移动到同一线程
    m_dataRequestTimer->moveToThread(thread);
    m_samplingRateCheckTimer->moveToThread(thread);

    logMessage(QString("GSR设备及其定时器已移动到线程: %1").arg(thread->objectName()));
}
bool GSRDevice::setSamplingRate(SamplingRateOption rate)
{
    if (!m_connected) {
        logMessage("错误: 设备未连接，无法设置采样率");
        emit errorOccurred("设备未连接，无法设置采样率");
        return false;
    }

    // 如果正在采集数据，先停止采集
    bool wasAcquiring = m_acquiring;
    if (wasAcquiring) {
        stopAcquisition();
    }

    // 记录新的采样率选项
    m_samplingRateOption = rate;

    // 根据选项设置实际采样率
    switch (rate) {
    case RATE_100HZ:
        m_samplingRate = 100;
        m_dataRequestInterval = 50; // 50ms，每秒请求20次数据
        break;
    case RATE_200HZ:
        m_samplingRate = 200;
        m_dataRequestInterval = 25; // 25ms，每秒请求40次数据
        break;
    case RATE_400HZ:
        m_samplingRate = 400;
        m_dataRequestInterval = 12; // 12ms，每秒请求约83次数据
        break;
    case RATE_800HZ:
        m_samplingRate = 800;
        m_dataRequestInterval = 6; // 6ms，每秒请求约166次数据
        break;
    }

    // 更新数据请求定时器间隔
    m_dataRequestTimer->setInterval(m_dataRequestInterval);

    // 发送命令到设备
    bool success = sendSamplingRateCommand(rate);

    // 如果之前正在采集，则重新启动采集
    if (wasAcquiring && success) {
        startAcquisition();
    }

    logMessage(QString("采样率已设置为 %1 Hz").arg(m_samplingRate));
    return success;
}

bool GSRDevice::sendSamplingRateCommand(SamplingRateOption rate)
{
    if (!m_connected || !m_uartService || !m_rxCharacteristic.isValid()) {
        return false;
    }

    // 准备命令数据
    QByteArray command;

    // 这里假设您的BLE设备接受特定格式的命令来设置采样率
    switch (rate) {
    case RATE_100HZ:
        command = QByteArray::fromHex("0100"); // 设置为模式0，100Hz
        break;
    case RATE_200HZ:
        command = QByteArray::fromHex("0200"); // 设置为模式2，200Hz
        break;
    case RATE_400HZ:
        command = QByteArray::fromHex("0400"); // 设置为模式4，400Hz
        break;
    case RATE_800HZ:
        command = QByteArray::fromHex("0600"); // 设置为模式6，800Hz
        break;
    }

    // 发送命令到设备
    m_uartService->writeCharacteristic(m_rxCharacteristic, command);

    // 等待设备响应
    QEventLoop loop;
    QTimer timeoutTimer;
    timeoutTimer.setSingleShot(true);

    QObject::connect(&timeoutTimer, &QTimer::timeout, &loop, &QEventLoop::quit);
    QObject::connect(this, &GSRDevice::dataReceived, &loop, &QEventLoop::quit);

    timeoutTimer.start(1000); // 1秒超时
    loop.exec();

    return timeoutTimer.isActive(); // 如果定时器仍在运行，说明收到了响应
}

QStringList GSRDevice::getAvailableSamplingRates()
{
    return QStringList() << "100 Hz" << "200 Hz" << "400 Hz" << "800 Hz";
}
